import { defineStore } from 'pinia'

export type CartItem = {
  id: number | string
  title: string
  image: string
  price: number
  qty: number
  attrs?: string
}

export interface CartState {
  items: CartItem[]
}

export const useCartStore = defineStore('cart', {
  state: (): CartState => ({
    items: [],
  }),
  getters: {
    totalCount: (state: CartState): number => state.items.reduce((sum: number, it: CartItem) => sum + it.qty, 0),
    totalAmount: (state: CartState): number => state.items.reduce((sum: number, it: CartItem) => sum + it.qty * it.price, 0),
  },
  actions: {
    add(item: CartItem): void {
      const exist = (this as unknown as CartState).items.find(i => i.id === item.id)
      if (exist) exist.qty += item.qty
      else (this as unknown as CartState).items.push({ ...item })
    },
    remove(id: CartItem['id']): void {
      (this as unknown as CartState).items = (this as unknown as CartState).items.filter(i => i.id !== id)
    },
    clear(): void {
      (this as unknown as CartState).items = []
    },
    updateQty(id: CartItem['id'], qty: number): void {
      const it = (this as unknown as CartState).items.find(i => i.id === id)
      if (it) it.qty = Math.max(1, qty)
    }
  },
  persist: {
    key: 'chaye-cart',
    storage: localStorage,
  }
}) 